<template>
  <div id="ShelfRecommended">
    <root name="ShelfRecommended">
      <SafeHeader
        v-bind="{
          title: '推荐上架',
          isBack: true,
          fixedTop: true,
        }"
      />
      <div class="shelfRecommended_wrap">
        <v-container class="px-2">
          <v-card outlined class="py-1">
            <v-row class="ma-0 mb-0">
              <v-col class="py-1">
                <v-text-field
                  id="tagBarcode"
                  autofocus
                  clearable
                  filled
                  :prepend-inner-icon="mdiCreditCardScan"
                  class="my-0 inputPlaceholder"
                  @keydown.13="scanBoxCode"
                  dense
                  background-color="#F8F8FF"
                  hide-details
                  v-model="currentUpperItem.boxCode"
                  placeholder="扫描追踪号"
                ></v-text-field>
              </v-col>
            </v-row>
            <v-row class="ma-0">
              <v-col cols="12" class="py-1">
                <v-text-field
                  label="物料"
                  class="my-0 inputPlaceholder"
                  clearable
                  :disabled="true"
                  v-model.trim="currentUpperItem.itemCode"
                  hide-details
                ></v-text-field>
              </v-col>
            </v-row>
            <v-row class="ma-0">
              <v-col cols="12" class="py-1">
                <v-text-field
                  label="批次"
                  class="my-0"
                  clearable
                  :disabled="true"
                  v-model.trim="currentUpperItem.batchName"
                  hide-details
                ></v-text-field>
              </v-col>
            </v-row>
            <v-row class="ma-0">
              <v-col cols="12" class="py-1">
                <v-text-field
                  label="待上架数量"
                  class="my-0"
                  type="number"
                  :disabled="true"
                  v-model.trim="currentUpperItem.srcQuantity"
                  hide-details
                ></v-text-field>
              </v-col>
              <!-- <v-col cols="6" class="py-1">
                <v-text-field
                  id="upperQty"
                  label="上架数量"
                  class="my-0"
                  type="number"
                  clearable
                  v-model.trim="currentUpperItem.quantity"
                  hide-details
                ></v-text-field>
              </v-col> -->
            </v-row>
            <v-row class="ma-0 mt-1">
              <v-col class="py-1" cols="9">
                <v-text-field
                  id="targetWorkCellCode"
                  clearable
                  filled
                  :prepend-inner-icon="mdiCreditCardScan"
                  class="my-0 inputPlaceholder"
                  @keydown.13="scanCellCode"
                  @change="handleCellChange"
                  dense
                  hide-details
                  background-color="#F8F8FF"
                  v-model="currentUpperItem.targetWorkCellCode"
                  placeholder="扫描上架库位"
                ></v-text-field>
              </v-col>
              <v-col class="py-1" cols="3">
                <v-btn dark depressed color="#FFC352" @click="submit"
                  >提交</v-btn
                >
                <!-- style="height: 22px" -->
              </v-col>
            </v-row>
          </v-card>
        </v-container>

        <!-- <v-container class="px-0 shelfRecommended_select" style="flex: 1">
          <v-data-table
            caption="推荐列表"
            no-data-text="暂无数据"
            hide-default-footer
            :headers="headers"
            :items="workCellList"
            disable-sort
            fixed-header
            item-key="id"
            single-select
            height="300"
            light
            class="pt-2 shelfRecommended_table"
            mobile-breakpoint="0"
            :loading="loading"
            loading-text="Loading... Please wait"
            @item-selected="handleSelect"
          >
          </v-data-table>
        </v-container> -->
        <!-- <div v-show="hidshow" class="footer">
          <v-bottom-navigation>
            <v-row class="ma-0 pa-2">
              <v-col class="pa-0">
                <v-btn
                  block
                  color="#193690"
                  dark
                  style="height: 100%; border-radius: 10px"
                  @click="submit"
                >
                  <span
                    style="color: #fff; font-size: 15px"
                    class="font-weight-bold"
                    >提交</span
                  >
                </v-btn>
              </v-col>
            </v-row>
          </v-bottom-navigation>
        </div> -->
      </div>
    </root>
    <v-overlay :value="overlay">
      <v-progress-circular indeterminate size="64"></v-progress-circular>
    </v-overlay>
  </div>
</template>

<script>
import Root from "@/components/Root.vue";
import SafeHeader from "../../components/safeHeader_wms";
import wms from "@/utils/business_wms";
import { printToJiaBo } from "@/static/print";
import { mdiCreditCardScan } from "@mdi/js";

// function debounce(fn, delay) {
//   let timer = null;
//   return function () {
//     // eslint-disable-next-line prefer-rest-params
//     let arg = arguments;

//     clearTimeout(timer);

//     timer = setTimeout(() => {
//       fn.apply(this, arg);
//     }, delay);
//   };
// }

export default {
  name: "ShelfRecommended",
  components: {
    SafeHeader,
    Root,
  },
  data() {
    return {
      mdiCreditCardScan: mdiCreditCardScan,

      // docmHeight: document.documentElement.clientHeight,
      // showHeight: document.documentElement.clientHeight,
      hidshow: true,
      overlay: false,
      loading: false,

      headers: [
        {
          text: "库区",
          align: "center",
          value: "areaName",
          class: "shelfRecommended_table_header",
        },
        {
          text: "库位",
          value: "cellCode",
          align: "center",
          class: "shelfRecommended_table_header",
        },
      ],

      currentUpperItem: {
        boxCode: "",
        srcQuantity: "",
        quantity: "",
        targetWorkCellCode: "",
        itemCode: "",
        itemName: "",
        batchName: "",
        inventoryId: "",
      },

      workCellList: [
        // {
        //   id: "1",
        //   cellCode: "TL_CCQ1-02-01-01",
        //   cellName: "TL_CCQ1-02-01-01",
        // },
        // {
        //   id: "2",
        //   cellCode: "TL_CCQ1-02-01-02",
        //   cellName: "TL_CCQ1-02-01-02",
        // },
      ],
      targetWorkCellCode: "", // 扫描库位编码
      timer: null,
    };
  },
  watch: {
    // showHeight: function () {
    //   if (this.docmHeight > this.showHeight) {
    //     this.hidshow = false;
    //   } else {
    //     this.hidshow = true;
    //   }
    // },
  },
  mounted() {
    // window.onresize = () => {
    //   return (() => {
    //     this.showHeight = document.body.clientHeight;
    //   })();
    // };
  },
  methods: {
    /* 扫描追踪号 */
    scanBoxCode() {
      //Step1.校验数据
      if (!this.currentUpperItem.boxCode) {
        return this.$root.api.api.toast({
          msg: "追踪号为空",
          location: "middle",
        });
      }
      //Step2.根据追踪号查询待上架库存
      this.overlay = true;
      wms
        .get({
          url: "/inventorys/toUpperStock",
          data: { boxCode: this.currentUpperItem.boxCode },
        })
        .then((res) => {
          this.overlay = false;
          if (res.status == 200 && res.data.code == 200) {
            // 未查询到
            let dataList = res.data.data.list;
            if (dataList.length < 1) {
              this.$root.api.api.toast({
                msg:
                  "根据[" +
                  this.currentUpperItem.boxCode +
                  "]未查询到待上架库存，请确认!",
                location: "middle",
                duration: 5000,
              });

              this.currentUpperItem.boxCode = "";
              document.getElementById("tagBarcode").focus();

              return false;
            } else if (dataList.length > 1) {
              return alert(
                "根据[" +
                  this.currentUpperItem.boxCode +
                  "]查询到多条数据，数据错误，请联系管理员!"
              );
            } else {
              //赋值
              let data = dataList[0];
              this.currentUpperItem.itemCode = data.itemCode; // 物料编码
              this.currentUpperItem.itemName = data.itemName; // 物料名称
              this.currentUpperItem.batchName = data.batchName; // 批次号
              this.currentUpperItem.srcQuantity = data.quantity; // 校验数量(收货单的还需收货的数量)
              this.currentUpperItem.quantity = data.quantity; // 校验数量(收货单的还需收货的数量)
              this.currentUpperItem.inventoryId = data.inventoryId; // 库存ID

              // 打开目标库位焦点
              document.getElementById("targetWorkCellCode").focus();
            }
          } else {
            alert("查询失败:" + res.data.message);
          }
        });

      //TODO: 传递到后台，后台给出推荐的库位
      // wms
      //   .get({
      //     url: "/transfer/upper/recommend",
      //     data: { boxCode: this.ctCode }
      //   })
      //   .then(res => {
      //     if (res.status == 200 && res.data.code == 200) {
      //       console.log(JSON.stringify(res.data));
      //       let recCells = res.data.data;
      //       console.log(recCells.length);
      //       for (let index = 0; index < recCells.length; index++) {
      //         let cellInfo = {};
      //         cellInfo.id = recCells[index].cellId;
      //         cellInfo.cellCode = recCells[index].cellCode;
      //         cellInfo.cellName = recCells[index].cellName;
      //         cellInfo.boxNum = recCells[index].boxNum;
      //         this.workCellList.push(cellInfo);
      //       }

      //       this.tableData1 = this.workCellList;
      //       document.getElementById("targetWorkCellCode").focus();
      //       this.overlay = false;
      //     } else {
      //       this.overlay = false;
      //       alert(res.data.message);
      //     }
      //   });
    },

    /* 扫描库位编码 */
    scanCellCode() {
      this.overlay = true;
      wms
        .get({
          url: "/inventorys/list",
          data: {
            cellCode: this.currentUpperItem.targetWorkCellCode,
          },
        })
        .then((res) => {
          this.overlay = false;
          if (res.status == 200 && res.data.code == 200) {
            console.log(JSON.stringify(res.data.data));
            let stockData = res.data.data.list;
            //卓品逻辑，要判断是否是电子料架，电子料架只能放一个料

            if (stockData.length == 0) {
              this.$root.api.api.toast({ msg: "无数据", location: "middle" });
              //卓品的电子料架推荐逻辑
              let cellCodes = [];
              cellCodes.push(this.currentUpperItem.targetWorkCellCode);
              let params = {
                cellCodes: cellCodes,
                time: 30,
                lighttype: 1, //亮灯
              };
              wms
                .post({
                  url: "/cell/infos/operate",
                  data: params,
                })
                .then((res) => {
                  this.overlay = false;
                  if (res.status === 200 && res.data.code === 200) {
                    //成功，不需要有任何提示
                  } else {
                    alert(res.data.message);
                  }
                  console.log(res);
                });
            } else {
              let startCellCodeStr =
                this.currentUpperItem.targetWorkCellCode.substr(0, 2);
              console.log(startCellCodeStr);
              if (startCellCodeStr != "zp") {
                this.$root.api.api.toast({
                  msg: "该库位已有库存",
                  location: "middle",
                  duration: 5000,
                });
                // alert("该库位已有库存");
                this.currentUpperItem.targetWorkCellCode = "";
              }
            }
            this.stockInfo = stockData;
          } else {
            alert(res.data.message);
          }
        });
    },

    /* 提交方法 */
    submit() {
      //Step1.校验数据是否完善
      if (
        !this.currentUpperItem.srcQuantity ||
        !this.currentUpperItem.targetWorkCellCode ||
        !this.currentUpperItem.quantity
      ) {
        return this.$root.api.api.toast({
          msg: "请确保以下数据完善：追踪号、上架库位!",
          location: "middle",
          duration: 3000,
        });
      }

      //Step2.提交
      let upperData = {
        upperList: [
          {
            fromInvId: this.currentUpperItem.inventoryId, //来源库存ID
            quantity: this.currentUpperItem.quantity, //上架数量
            cellCode: this.currentUpperItem.targetWorkCellCode, //目标库位
          },
        ],
      };

      this.overlay = true;
      wms
        .post({
          url: "/transfer/create/upper",
          data: upperData,
        })
        .then((res) => {
          this.overlay = false;
          if (res.status === 200 && res.data.code === 200) {
            //Step3.提交成功 提示成功；清空数据；判断是否需要打印
            alert("上架成功!");

            if (
              this.currentUpperItem.quantity !=
              this.currentUpperItem.srcQuantity
            ) {
              let retData = res.data.data;
              if (
                window.navigator.userAgent.toLowerCase().includes("apicloud")
              ) {
                printToJiaBo(
                  retData[0].itemCode,
                  retData[0].itemName,
                  retData[0].batchName,
                  this.currentUpperItem.quantity,
                  "null",
                  1
                );
                printToJiaBo(
                  retData[0].itemCode,
                  retData[0].itemName,
                  retData[0].batchName,
                  this.currentUpperItem.srcQuantity -
                    this.currentUpperItem.quantity,
                  "null",
                  1
                );
              }
            }

            //点击后清空数据
            Object.keys(this.currentUpperItem).forEach(
              (key) => (this.currentUpperItem[key] = "")
            );
            this.workCellList = [];
            this.targetWorkCellCode = "";
            document.getElementById("tagBarcode").focus();
          } else {
            alert(res.data.message);
          }
          console.log(res);
        });
    },

    //TODO: 推荐库位的逻辑
    handleSelect(e) {
      this.targetWorkCellCode = e.item.cellCode;
      console.log(e.item.cellCode);
    },
    handleCellChange(e) {
      console.log(e);
      // if (e) this.searchCellList(e);
    },

    // 查询库位列表中有没有相同的
    searchCellList(e) {
      let cellInTable;
      this.workCellList.forEach((item, index) => {
        if (item.cellCode === e) {
          cellInTable = index;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.footer {
  position: absolute;
  padding-top: 65px;
  width: 100%;
  bottom: 0;
}
</style>

<style lang="sass" scoped>
.scanContainer
  >.row
    margin: 0
    padding: 10px

.shelfRecommended_table
  ::v-deep .v-data-table__mobile-table-row
    margin: 4px 8px
    background-color: #e8e8e8f1
  ::v-deep .v-data-table__mobile-row
    min-height: 28px !important
    // 暂无数据的显示
    ::v-deep .v-data-table__empty-wrapper
      display: flex
      justify-content: center
      align-items: center
      td
        line-height: 48px
  ::v-deep .shelfRecommended_table_header
    font-size: 14px !important

.inputPlaceholder
  ::v-deep.v-text-field__slot
    input::-webkit-input-placeholder
      font-size: 15px
    input::-moz-placeholder
      font-size: 15px
    input:-moz-placeholder
      font-size: 15px
    input:-ms-input-placeholder
      font-size: 15px
.treeview_dept
  height: 120px
  overflow-y: scroll
.shelfRecommended_wrap
  height: 100%
  display: flex
  flex-direction: column
  justify-content: space-between
.shelfRecommended_select
  height: 100%
  max-height: 400px
  .shelfRecommended_select_title
    font-size: 15px
    font-weight: bold
  .v-card
    height: 100%
  // background-color: #fff
  .shelfRecommended_select_content
    flex: 1
    max-height: 300px
    overflow: auto
    border-radius: 8px
    background-color: #f2f3f5
    border: 1px solid #dcdcde
    .v-input--radio-group--column .v-radio:not(:last-child):not(:only-child)
      margin-bottom: 12px
    .v-input--selection-controls
      margin-top: 0
    ::v-deep .v-radio
      display: flex
      align-items: center
      flex-wrap: nowrap
      .v-input--selection-controls__input
        height: 32px
        width: 32px
      .v-icon__svg
        height: 30px
        width: 30px
      .v-label
        font-size: 18px
</style>
